import time
from camera_cal.ipcamCapture import ipcamCapture

# ffmpeg get realtime picture
def getpciture():
    URL = "rtsp://admin:aA123321Aa@192.168.1.102:554/Streaming/Channels/101?transportmode=unicast"
    # URL = "rtmp://rtmp.open.ys7.com/openlive/143159dfa7ba4545900dc6cba0416200.hd"
    cam = ipcamCapture(URL)
    cam.start()  # open webcamera
    time.sleep(1)
    img = cam.getframe()
    # frame = cv2.undistort(img, mtx, dist, None, mtx)
    # cv2.imshow("img", img)
    # cv2.waitKey(0)
    cam.stop()   # close camera
    return img

# write data
def writefile_b_new(url, angle, center):
    with open(url, 'w') as f:
        f.write('angle={}'.format(angle) + '\n')  # angle
        f.write('x={}'.format(center[0]) + '\n')  # x
        f.write('y={}'.format(center[1]) + '\n')  # y


# read data
def readfile_b_new(url):
    with open(url, 'r') as f:
        list = f.readlines()
        if len(list) > 0:
            for line in list:
                # print(line)
                if line.split('=')[0] == 'angle':
                    angle = line.split('=')[1].strip()
                elif line.split('=')[0] == 'x':
                    x = line.split('=')[1].strip()
                elif line.split('=')[0] == 'y':
                    y = line.split('=')[1].strip()
                else:
                    pass
        else:
            return 'false'
    return float(angle), float(x), float(y)


def writeAB(url, ctr, delta_angle, delta_x, delta_y):
    with open(url, 'a') as f:
        f.write('ctr={}'.format(ctr) + '\n')
        f.write('delta_angle={}'.format(delta_angle) + '\n')  # delta_angle
        f.write('delta_x={}'.format(delta_x) + '\n')  # delta_x
        f.write('delta_y={}'.format(delta_y) + '\n')  # delta_y


def readAB(url, str, i):
    st = []
    with open(url, 'r') as f:
        for line in f.readlines():
            if line.split('=')[0] == str:
                st.append(line.split('=')[1].strip())
            else:
                pass
    return float(st[i])

if __name__ == "__main__":
    getpciture()
